import sys
import io
import os

try:
    from reportlab.platypus import Paragraph, Frame, KeepInFrame, SimpleDocTemplate, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.pagesizes import A4, landscape
    from PyPDF2 import PdfFileWriter, PdfFileReader
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.pdfbase import pdfmetrics
    from googletrans import Translator
    import fitz
except:
    os.system('pip3 install reportlab PyPDF2 googletrans==4.0.0-rc1 pymupdf')
    from reportlab.platypus import Paragraph, Frame, KeepInFrame, SimpleDocTemplate, Image
    from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
    from reportlab.lib.pagesizes import A4, landscape
    from PyPDF2 import PdfFileWriter, PdfFileReader
    from reportlab.pdfbase.ttfonts import TTFont
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.pdfbase import pdfmetrics
    from googletrans import Translator
    import fitz
from time import sleep

try:
    pdfmetrics.registerFont(TTFont('font_file', 'msyh.ttc'))
except:
    print("The Font File not found. Press Any Key to Exit")
    input()
    exit(0)

def main(a):
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(fontName='font_file', name='font_fromfile', leading=20*0.9, fontsize=20))

    translator = Translator(service_urls=[r'translate.google.cn'], user_agent='Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Edg/87.0.664.66')

    output = PdfFileWriter()

    filetodo = a

    if not os.path.isfile(filetodo):
        print('It is not a file. Press Any Key to Exit')
        input()
        sys.exit(0)

    pdf = fitz.open(filetodo)

    
    for xref in range(1, pdf.xref_length()):
        if stream := pdf.xref_stream(xref):
            stream = stream.replace(b'Td', b' 3 Tr Td').replace(b' Tm', b' 3 Tr Tm')
            pdf.update_stream(xref, stream)


    pdf.save('temp.'+os.path.basename(filetodo))

    temp_empty=open('temp.'+os.path.basename(filetodo),'rb')
    base_pdf = PdfFileReader(temp_empty)



    i_base_page = 0
    i_translator = 0
    while i_base_page < base_pdf.numPages:
        if_skip_thispage = False

        doc = fitz.open(filetodo)
        doc_page = doc[i_base_page]
        # page.getText("block")
        #print(page.getImageList())
        context = doc_page.getText("blocks")
        # print(context)
        context1 = []
        page_size = doc_page.MediaBox[2:4]
        # print(page_size)

        for elem in context:
            context1.append(elem[4].replace('\n',''))

        context1 = '\n\n\n'.join(context1)

        context2 = []
        count_chars = 0
        i_last = ''
        context1=context1.split('. ')
        for i in context1:
            if len(i_last) < 1800:
                i_last = i_last + i + '. '
                continue
            context2.append(i_last)
            i_translator += 1
            print('Queue %s has chars: %s' %(i_translator, len(i_last)))
            count_chars += len(i_last)
            i_last = '' + i + '. '
            if len(i_last) >= 1800:
                context2.append(i_last)
                i_translator += 1
                print('Queue %s has chars: %s' %(i_translator, len(i_last)))
                count_chars += len(i_last)
                i_last = ''

        i_last=i_last.strip('\n. ')
        context2.append(i_last)
        i_translator += 1
        print('Queue %s has chars: %s' %(i_translator, len(i_last)))
        count_chars += len(i_last)

        print('Current page chars: %s' %count_chars)
        # print(context2)

        if count_chars < 5:
            print('Current page chars are less 5. Skip translate.')
            if_skip_thispage = True



        context3 = []
        for i3 in context2:
            if if_skip_thispage == True:
                context3.append(i3)
            if if_skip_thispage == False:
                s=None
                while s is None:
                    s=translator.translate(i3,src='en',dest='zh-cn').text
                    sleep(1)
                context3.append(s)

        # print(context3)

        context3 = ''.join(context3)
        context3 = context3.split('\n\n\n')
        # print(context3)

        # open('4.trans.txt',encoding='UTF8',mode='w').write('\n'.join(context3))
        # context3 = open('4.trans.txt',encoding='UTF8',mode='r').read().split('\n')
        # print(len(context3))


        
        packet = io.BytesIO()
        c = Canvas(packet, pagesize=page_size)
        len_context3 = len(context3)
        i_tran = 0
        while i_tran < len_context3:
            context_i = context[i_tran][:4]
            p0 = context_i[0]
            p1 = page_size[1]-context_i[3]
            # 注意：Frame从下向上绘制，p1=文本框底部位置
            p2 = context_i[2]-context_i[0]
            p3 = context_i[3]-context_i[1]
            try:
                story = [Paragraph(context3[i_tran], styles['font_fromfile'])]
            except:
                story = [Paragraph(context3[i_tran].replace(r'&',r'&amp;').replace(r'<',r'&lt;').replace(r'>',r'&gt;'), styles['font_fromfile'])]

            Frame(p0, p1, p2, p3, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, showBoundary=0).addFromList([KeepInFrame(0, 0, story)], c)

            #print(context3[i_tran])
            i_tran += 1

        c.save()

        packet.seek(0)
        new_page = PdfFileReader(packet)
        base_page = base_pdf.getPage(i_base_page)
        base_page.mergePage(new_page.getPage(0))
        output.addPage(base_page)
        
        i_base_page += 1

    output.write(open('tans.'+os.path.basename(filetodo), 'wb'))

    temp_empty.close()
    os.remove(temp_empty.name)


if __name__ == "__main__":
    for i in sys.argv[1:]:
        main(i.strip('\'\"\\').rstrip("/"))
